package org.learn.controller;

import org.learn.config.Jwt;
import org.learn.entity.User;
import org.learn.entity.UserList;
import org.learn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/findAll",method = RequestMethod.GET)
    public List<UserList> findAll(){
        return this.userService.findAll();
    }

    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    public Integer insert(@RequestBody UserList userList){
        Integer insert = userService.insert(userList.getId(),userList.getName());
        return insert;
    }

    @RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    public Integer delete(@RequestBody UserList userList){
        Integer delete = userService.delete(userList.getId());
        return delete;
    }
    @RequestMapping(value = "put",method = RequestMethod.PUT)
    public Integer put(@RequestBody UserList userList){
        Integer put = userService.put(userList.getId(),userList.getName());
        return put;
    }

    @PostMapping(value = "/login")
    public String login(@RequestBody User user){
        Integer login = userService.login(user.getUsername(), user.getPassword());
        if(login == 0){
            return "登录失败";
        }else {
            //登录成功，生成JWT令牌
            Map<String,Object> claims = new HashMap<>();
            claims.put("username",user.getUsername());
            claims.put("password",user.getPassword());
            String s = Jwt.genJWT(claims);
            return s;
        }
    }



}
